from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
from .router import PathRouter, Redirect, InternalServerError

class Server(object):

    def __init__(self, host, port):
        self.__host = host
        self.__port = port
        self.__router = PathRouter()
        
    def get_router(self):
        return self.__router
        
    def __app(self, env, start_response):
        path = env['PATH_INFO']
     
        post = env['wsgi.input']
        
        if env.get('CONTENT_LENGTH', '0'):
            length = int(env.get('CONTENT_LENGTH', '0'))
            post = env['wsgi.input'].read(length)
        else:
            post = ''
        status, headers, body = self.__router.dispatch_request(path, env, post)
        
        start_response(status, list(headers.items()))
        
        return [str(body)]
       
    def start(self):
        httpd = make_server(self.__host, self.__port, self.__app)
        httpd.serve_forever()

    
